import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import unocss from "unocss/vite";
import AutoImport from "unplugin-auto-import/vite";
import * as process from "process";
import simpleHtmlPlugin from "vite-plugin-simple-html";
import path from "path";
import { execSync } from "child_process";
import * as fs from "fs";
import { PluginIcons, PluginPagePaths } from "./build/plugins";

// https://vite.dev/config/
export default defineConfig(({ command, mode }) => {
  const viteEnv = loadEnv(mode, process.cwd());
  const isBuild = command === "build";
  const { VITE_PROXY_TARGET, VITE_TITLE } = viteEnv;

  if (isBuild) {
    fs.readFile("./public/version.json", "utf8", (err, data) => {
      if (!err) {
        let obj;
        try {
          obj = JSON.parse(data);
          obj.version = execSync("git rev-parse --short HEAD")
            .toString()
            .trim();
        } catch (error) {
          throw Error(error);
        }
        // 在 JSON 序列化成功才会去同步修改 version.json 文件内容
        if (obj) fs.writeFileSync("./public/version.json", JSON.stringify(obj));
        // 没有找到文件，抛出异常
      } else throw Error(err?.message);
    });
  }

  return {
    resolve: {
      alias: {
        "@": path.resolve(process.cwd(), "src"),
        "~": path.resolve(process.cwd()),
      },
    },
    plugins: [
      vue(),
      unocss(),
      AutoImport({
        imports: ["vue", "vue-router"],
        dts: "src/auto-import.ts",
      }),
      PluginIcons(),
      PluginPagePaths(),
      simpleHtmlPlugin({
        minify: isBuild,
        inject: {
          data: {
            title: VITE_TITLE,
          },
        },
      }),
    ],
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/styles/variables.scss" as *;`,
        },
      },
    },
    server: {
      port: 3800,
      proxy: {
        "/api": {
          target: VITE_PROXY_TARGET,
          changeOrigin: true,
        },
      },
    },
    build: {
      chunkSizeWarningLimit: 1024, // chunk 大小警告的限制（单位kb）
    },
  };
});
